package xhwl.hmo.mall.ui.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dreamlive.upmarqueeview.UPMarqueeView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle.components.support.RxFragmentActivity;

import java.util.ArrayList;
import java.util.List;

import xhwl.hmo.mall.R;
import xhwl.hmo.mall.adapter.HorizontalRecycleViewAdapter;
import xhwl.hmo.mall.adapter.RecommendRecycleViewAdapter;
import xhwl.hmo.mall.holder.MZHolderCreator;
import xhwl.hmo.mall.holder.MZViewHolder;
import xhwl.hmo.mall.http.api.HMOBannerApi;
import xhwl.hmo.mall.http.api.HMONewsListApi;
import xhwl.hmo.mall.http.api.NewProductApi;
import xhwl.hmo.mall.http.api.RecommendApi;
import xhwl.hmo.mall.http.bean.resp.HMOBannerResp;
import xhwl.hmo.mall.http.bean.resp.HmoNewsResp;
import xhwl.hmo.mall.http.bean.resp.HttpResp;
import xhwl.hmo.mall.http.bean.resp.NewProductResp;
import xhwl.hmo.mall.http.bean.resp.RecommendResp;
import xhwl.hmo.mall.ui.SuiteProductsDetailActivity;
import xhwl.hmo.mall.ui.WebViewActivity;
import xhwl.hmo.mall.utils.AppUtil;
import xhwl.hmo.mall.utils.ToastUtil;
import xhwl.hmo.mall.views.MZBannerView;
import xhwl.hmo.mall.views.MyListView;
import xhwl.retrofitrx.BaseApi;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

import static xhwl.hmo.mall.ui.WebViewActivity.EXTRA_TITLE;
import static xhwl.hmo.mall.ui.WebViewActivity.EXTRA_URL;

/**
 * A simple {@link Fragment} subclass.
 */
public class RecommendFragment extends BaseFragment {
    private String hmoPic;
    //横向滑动
    private RecyclerView hor_RecyclerView;
    HorizontalRecycleViewAdapter horizontalRecycleViewAdapter;
    UPMarqueeView upview1;
    List<View> views = new ArrayList<>();
    List<HmoNewsResp> data=new ArrayList<>();
    //精品推荐List
    List<RecommendResp> recommendRespList = new ArrayList<>();

    List<NewProductResp> newProductdata = new ArrayList<>();
    //轮播图
    private MZBannerView mMZBanner;
    List<String> bannerList=new ArrayList<>();
    List<HMOBannerResp> hmoBannerRespList = new ArrayList<>();
    //精品推荐
    private MyListView lv_recommend;
    RecommendRecycleViewAdapter recommendRecycleViewAdapter;
    int page_num = 1;
    ScrollView sll_view;
    RefreshLayout refreshLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_recommend, container, false);
    }

    @Override
    protected void initView(View view) {
        sll_view = (ScrollView) view.findViewById(R.id.sll_view);
        sll_view.smoothScrollTo(0,20);
        refreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);

        lv_recommend = (MyListView) view.findViewById(R.id.lv_recommend);
        //横向滑动
        hor_RecyclerView = (RecyclerView) view.findViewById(R.id.id_recyclerview_horizontal);
        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        hor_RecyclerView.setLayoutManager(linearLayoutManager);
        upview1 = (UPMarqueeView) view.findViewById(R.id.upview1);

        //轮播图
        mMZBanner = (MZBannerView) view.findViewById(R.id.banner);
        mMZBanner.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
            @Override
            public void onPageClick(View view, int position) {
                if(hmoBannerRespList.get(position).LINK_ADD!="") {
                    AppUtil.startWebViewActivity(mActivity, hmoBannerRespList.get(position).LINK_ADD, "");
                }else{
                    Intent intent = new Intent(getActivity(), SuiteProductsDetailActivity.class);
                    intent.putExtra("GOOD_ID", hmoBannerRespList.get(position).GOODS_ID != null ? hmoBannerRespList.get(position).GOODS_ID : "");
                    startActivity(intent);
                }
                }
        });
        mMZBanner.addPageChangeLisnter(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                Log.e(TAG, "----->addPageChangeLisnter:" + position + "positionOffset:" + positionOffset + "positionOffsetPixels:" + positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
//                Log.e(TAG, "addPageChangeLisnter:" + position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        recommendRecycleViewAdapter = new RecommendRecycleViewAdapter(mActivity, recommendRespList);
        lv_recommend.setAdapter(recommendRecycleViewAdapter);
        lv_recommend.setFocusable(false);


    }

    public static class BannerViewHolder implements MZViewHolder<String> {
        private ImageView mImageView;
        int page_num = 1;

        @Override
        public View createView(Context context) {
            // 返回页面布局文件
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item, null);
            mImageView = (ImageView) view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(Context context, int position, String data) {
            // 数据绑定
//            mImageView.setImageResource();
            Glide.with(context).load(data).crossFade().into(mImageView);
            ;

        }
    }

    @Override
    protected void initListener() {

        lv_recommend.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), SuiteProductsDetailActivity.class);
                intent.putExtra("GOOD_ID", recommendRespList.get(position).GOODS_ID != null ? recommendRespList.get(position).GOODS_ID : "");
                startActivity(intent);
            }
        });
//        refreshLayout.setRefreshFooter(new ClassicsFooter(mActivity).setDrawableSize(20));
//        refreshLayout.setEnableAutoLoadmore(true);
//        RecommentRefreshHeader header=new RecommentRefreshHeader(mActivity);
//        refreshLayout.setRefreshHeader(header);
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                recommend(page_num + 1);
            }
        });
//        refreshLayout.setHeaderHeightPx(header.getHeaderHeight());
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                recommend(1);
            }
        });
    }

    @Override
    protected void loadData() {
        recommend(1);
        initHmoData();
        hmoBannerURL();
        newProduct();
    }

    private void recommend(final int page) {
        BaseApi api = new RecommendApi(page);
        HttpManager.getInstance().dealHttp((RxFragmentActivity) mActivity, api, new OnNextListener<HttpResp<ArrayList<RecommendResp>>>() {
            @Override
            public void onNext(HttpResp<ArrayList<RecommendResp>> recommendResp) {
                if (page > 1) {
                    refreshLayout.finishLoadmore();
                }else
                {
                    refreshLayout.finishRefresh();
                }
                if (recommendResp.isOk()) {
                    if (recommendResp.data.size() > 0) {
                        page_num = page;
                        if(page==1)
                        {
                            recommendRespList.clear();
                        }
                        recommendRespList.addAll(recommendResp.data);
                        recommendRecycleViewAdapter.notifyDataSetChanged();
                    } else {
//                        ToastUtil.showToast(mActivity, getString(R.string.no_more_data));
//                        refreshLayout.setEnableLoadmore(false);
                    }
                } else {
                    ToastUtil.showToast(mActivity, recommendResp.message);
                }

            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                if (page > 1) {
                    refreshLayout.finishLoadmore();
                }else
                {
                    refreshLayout.finishRefresh();
                }
            }
        });
    }

    private void initHmoData() {
        BaseApi api = new HMONewsListApi();
        HttpManager.getInstance().dealHttp((RxFragmentActivity) mActivity, api, new OnNextListener<HttpResp<ArrayList<HmoNewsResp>>>() {
            @Override
            public void onNext(HttpResp<ArrayList<HmoNewsResp>> hmoNewsResps) {
                if (hmoNewsResps.isOk()) {
                    data.clear();
                    if(hmoNewsResps.data!=null&&hmoNewsResps.data.size()>0){
                        data.addAll(hmoNewsResps.data);
                    }
                    initHmoView();
                }

            }
        });

    }

    /*
    新品首发
     */
    private void newProduct() {
        BaseApi api = new NewProductApi();
        HttpManager.getInstance().dealHttp((RxFragmentActivity) mActivity, api, new OnNextListener<HttpResp<ArrayList<NewProductResp>>>() {
            @Override
            public void onNext(HttpResp<ArrayList<NewProductResp>> newProductResp) {
                if (newProductResp.isOk()) {
                    newProductdata.clear();
                    for (int i = 0; i < newProductResp.data.size(); i++) {
                        newProductdata.add(newProductResp.data.get(i));
                    }
                    horizontalRecycleViewAdapter = new HorizontalRecycleViewAdapter(getActivity(), newProductdata);
                    hor_RecyclerView.setAdapter(horizontalRecycleViewAdapter);
                    horizontalRecycleViewAdapter.setOnItemClickLitener(new HorizontalRecycleViewAdapter.OnItemClickLitener() {
                        @Override
                        public void onItemClick(int position) {
                            Intent intent = new Intent(getActivity(), SuiteProductsDetailActivity.class);
                            intent.putExtra("GOOD_ID", newProductdata.get(position).GOODS_ID != null ? newProductdata.get(position).GOODS_ID : "");
                            startActivity(intent);
                        }
                    });
                }

            }
        });
    }

    private void initHmoView() {
        setView();
        upview1.setViews(views);
        /**
         * 设置item_view的监听
         */
        upview1.setOnItemClickListener(new UPMarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View view) {
                //进入头条页面
                Intent intent=new Intent();
                intent.setClass(getActivity(), WebViewActivity.class);
                intent.putExtra(EXTRA_URL,data.get(position).NOTICE_URL.replace("&amp;","&"));
                intent.putExtra(EXTRA_TITLE,data.get(position).NOTICE_TITLE);
                startActivity(intent);

            }
        });
    }

    private void setView() {
        for (int i = 0; i < data.size(); i = i + 1) {
            final int position = i;
            //设置滚动的单个布局
            LinearLayout moreView = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.item_hmo_view, null);
            //初始化布局的控件
            TextView tv1 = (TextView) moreView.findViewById(R.id.tv1);


            /**
             * 设置监听
             */
            moreView.findViewById(R.id.rl).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //进入头条页面
                    Intent intent=new Intent();
                    intent.setClass(getActivity(), WebViewActivity.class);
                    intent.putExtra(EXTRA_URL,data.get(position).NOTICE_URL.replace("&amp;","&"));
                    intent.putExtra(EXTRA_TITLE,data.get(position).NOTICE_TITLE);
                    startActivity(intent);

                }
            });
            //进行对控件赋值
            tv1.setText(data.get(i).NOTICE_TITLE.toString());

            //添加到循环滚动数组里面去
            views.add(moreView);
        }
    }

    private void hmoBannerURL() {
        BaseApi api = new HMOBannerApi();
        HttpManager.getInstance().dealHttp((RxFragmentActivity) getActivity(), api, new OnNextListener<HttpResp<ArrayList<HMOBannerResp>>>() {

            @Override
            public void onNext(HttpResp<ArrayList<HMOBannerResp>> hmoBannerResp) {
                if (hmoBannerResp.isOk()) {
                    bannerList.clear();
                    hmoBannerRespList.clear();
                    for (int i = 0; i < hmoBannerResp.data.size(); i++) {
                        hmoPic = hmoBannerResp.data.get(i).PIC_ADD;
                        bannerList.add(hmoPic);
                        hmoBannerRespList.add(hmoBannerResp.data.get(i));
                    }

                    mMZBanner.setIndicatorVisible(false);
                    mMZBanner.setPages(bannerList, new MZHolderCreator<BannerViewHolder>() {
                        @Override
                        public BannerViewHolder createViewHolder() {
                            return new BannerViewHolder();
                        }
                    });
                    mMZBanner.start();
                }

            }
        });
    }


//    @Override
//    public void onPause() {
//        super.onPause();
//        mMZBanner.pause();
//    }

}
